<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, nextTick, watch, reactive } from 'vue'
import { ElTree, ElInput, ElDivider, ElTag, ElUpload, ElIcon, ElMessage } from 'element-plus'
import { selectionType } from '@/api/login/types'
import { getUserListApi } from '@/api/department'
import {
  GetCoursePlansApi,
  DeleteCoursesPlanApi,
  AddCoursePlanApi,
  UpdateCoursePlanApi,
  GetUndoneCoursesApi,
  PalyVideoApi
} from '@/api/course'

import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import Write from './components/CoursePlanWrite.vue'
import Detail from './components/CoursePlanDetail.vue'
import { Dialog } from '@/components/Dialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'

import { useButtonPermiss } from '@/utils/buttonpermiss'
const haspermiss = ref<String[]>([])
const getUseButtonPermiss = () => {
  useButtonPermiss().then((res) => {
    haspermiss.value = res
  })
}
getUseButtonPermiss()

import { VideoDt } from '@/api/course/type'
import lookVideos from '@/views/examination/components/lookVideos.vue'

// console.log('uploadUrl', uploadUrl)
const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await GetCoursePlansApi({
      pageNo: unref(currentPage),
      pageRow: unref(pageSize),
      pageModel: { ...unref(searchParams) }
    })

    return {
      list: res.data.pageModels || [],
      total: res.data.totalCount || 0
    }
  },
  fetchDelApi: async () => {
    const res = await DeleteCoursesPlanApi(unref(ids))
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const typeList = ref<selectionType[]>([])
interface users {
  label: String
  value: String
  guid: String
  UserNo: String
}
// const usersList = ref<users[]>([])
// const GetCourseTypes = async () => {
//   // const res = await GetUndoneCoursesApi()
//   // res.data?.map((item) => {
//   //   typeList.value.push({
//   //     label: item.courseName,
//   //     value: item.guid
//   //   })
//   // })
//   const dt = await getUserListApi({ pageFlag: false })
//   let uList: users[] = []
//   dt.data.pageModels?.map((item) => {
//     uList.push({
//       label: item.userNo + '  ' + item.userName,
//       value: item.userNo + '$' + item.userName, // item.guid, //
//       guid: item.guid,
//       UserNo: item.userNo
//     })
//   })
//   usersList.value = uList
// }
// GetCourseTypes()
const chooes = ref<String[]>([])
const selectRef = ref()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('userDemo.index'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'index'
    }
  },

  {
    field: 'courseName',
    label: '课程名称',
    // search: {
    //   hidden: true
    // },
    form: {
      hidden: true
    },
    sortable: true
  },
  {
    field: 'planTime',
    label: '计划时间',
    search: {
      hidden: true
    },
    form: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        StartPlaceholder: 'Start date',
        EndPlaceholder: 'End date'
      }
    },
    table: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        StartPlaceholder: 'Start date',
        EndPlaceholder: 'End date'
      }
    },
    sortable: true
  },
  {
    field: 'teacherUsers',
    label: '计划讲师',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    slots: {
      default: (data: any) => {
        let arr: string[] = []
        if (data.row.teacherUsers) {
          JSON.parse(data.row.teacherUsers).map((i) => {
            arr.push(i.UserName)
          })
        }
        return <>{arr.toString()}</>
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          let arr: string[] = []
          if (data.teacherUsers) {
            JSON.parse(data.teacherUsers).map((i) => {
              arr.push(i.UserName)
            })
          }
          return <>{arr.toString()}</>
        }
      }
    },
    sortable: true
  },
  {
    field: 'examTeacher',
    label: '讲师',
    form: {
      hidden: true
    },
    sortable: true,
    slots: {
      default: (data: any) => {
        return <>{JSON.parse(data.row.examTeacher)?.UserName || ''}</>
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          return <>{JSON.parse(data.examTeacher)?.UserName || ''}</>
        }
      }
    }
  },
  {
    field: 'planUsersGuid',
    label: '参加人员',

    search: {
      hidden: true
    },
    slots: {
      default: (data: any) => {
        let arr: string[] = []
        if (data.row.planUsers) {
          JSON.parse(data.row.planUsers).map((i) => {
            arr.push(i.UserName)
          })
        }
        return <>{arr.toString()}</>
      }
    },
    detail: {
      hidden: true
    },
    sortable: true,
    table: { hidden: true }
  },
  {
    field: 'planUsersGuid',
    label: '计划学员数量',
    search: {
      hidden: true
    },
    slots: {
      default: (data: any) => {
        let arr: string[] = []
        if (data.row.planUsers) {
          JSON.parse(data.row.planUsers).map((i) => {
            arr.push(i.UserName)
          })
        }
        return <>{arr.length}</>
      }
    },
    detail: {
      //hidden: true
      slots: {
        default: (data: any) => {
          let arr: string[] = []
          if (data.planUsers) {
            JSON.parse(data.planUsers).map((i) => {
              arr.push(i.UserName)
            })
          }
          return <>{arr.length}</>
        }
      }
    },
    sortable: true
  },
  {
    field: 'planOrderNum',
    label: '培训次数',
    search: {
      hidden: true
    },
    // detail: {
    // slots: {
    //   default: (data: any) => {
    //     let arr: string[] = []
    //     if (data.examUsers) {
    //       JSON.parse(data.examUsers).map((i) => {
    //         arr.push(i.UserName)
    //       })
    //     }
    //     return <>{arr.length}</>
    //   }
    // }
    // },
    table: { hidden: true }
  },
  {
    field: 'releasePlanCount',
    label: '下发数量',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },

    sortable: true
  },
  {
    field: 'releaseExamCount',
    label: '已下发数量',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },

    sortable: true
  },
  // {
  //   field: 'planContent',
  //   label: '培训内容',
  //   search: {
  //     hidden: true
  //   }
  // },
  {
    field: 'planStatus',
    label: t('menu.status'),
    width: '80px',
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElTag size="small" type={data.row.planStatus === 0 ? 'danger' : 'success'}>
              {data.row.planStatus === 1 ? t('userDemo.over') : t('userDemo.naver')}
            </ElTag>
          </>
        )
      }
    },
    form: {
      hidden: true
    },
    detail: {
      slots: {
        default: (data) => {
          return <>{data.planStatus === 1 ? t('userDemo.over') : t('userDemo.naver')}</>
        }
      }
    },
    search: {
      component: 'Select',
      value: [],
      componentProps: {
        placeholder: '请选择'
      },
      optionApi: async () => {
        return [
          { label: t('userDemo.over'), value: 1 },
          { label: t('userDemo.naver'), value: 0 }
        ]
      }
    }
  },
  {
    field: 'planReleaseStatus',
    label: t('menu.ostatus'),
    width: '100px',
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElTag size="small" type={data.row.planReleaseStatus === 1 ? 'success' : 'danger'}>
              {data.row.planReleaseStatus === 1 ? t('userDemo.over') : t('userDemo.naver')}
            </ElTag>
          </>
        )
      }
    },
    form: {
      hidden: true
    },
    detail: {
      slots: {
        default: (data) => {
          return <>{data.planReleaseStatus === 1 ? t('userDemo.over') : t('userDemo.naver')}</>
        }
      }
    },
    search: {
      component: 'Select',
      value: [],
      componentProps: {
        placeholder: '请选择'
      },
      optionApi: async () => {
        return [
          { label: t('userDemo.over'), value: 1 },
          { label: t('userDemo.naver'), value: 0 }
        ]
      }
    }
  },
  // {
  // field: 'planUsersGuid',
  // label: '实际参加人员数量',
  // search: {
  // hidden: true
  // },
  // detail: {
  // slots: {
  // default: (data: any) => {
  // let arr: string[] = []
  // if (data.examUsers) {
  // JSON.parse(data.examUsers).map((i) => {
  // arr.push(i.UserName)
  // })
  // }
  // return <>{arr.length}</>
  // }
  // }
  // },
  // table: { hidden: true }
  // },
  // {
  // field: 'examUsers',
  // label: '实际参加人员',
  // form: {
  // hidden: true
  // },
  // search: {
  // hidden: true
  // },
  // detail: {
  // slots: {
  // default: (data: any) => {
  // let arr: string[] = []
  // if (data.examUsers) {
  // JSON.parse(data.examUsers).map((i) => {
  // arr.push(i.UserName)
  // })
  // }
  // return <>{arr.toString()}</>
  // }
  // }
  // },
  // table: { hidden: true }
  // },
  {
    field: 'isExam',
    label: '及格线',
    width: '84px',
    slots: {
      default: (data: any) => {
        return data.row.isExam === 1 ? data.row.resitScore : ''
      }
    },
    form: {
      hidden: true
    },
    detail: {
      slots: {
        default: (data) => {
          console.log(data)
          return <>{data.isExam ? data.resitScore : ''}</>
        }
      }
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'isMissExam',
    label: '缺席可参加考试',
    width: '84px',

    form: {
      hidden: true
    },
    detail: {
      slots: {
        default: (data) => {
          console.log(data)
          return <>{data.isMissExam ? '是' : '否'}</>
        }
      }
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'createTime',
    label: '创建时间',
    search: {
      hidden: true
    },
    sortable: true,
    detail: {
      hidden: true
    }
  },
  // {
  //   field: 'remark',
  //   label: t('common.remark'),
  //   form: {
  //     component: 'Input'
  //   },
  //   search: {
  //     hidden: true
  //   }
  // },
  {
    field: 'date',
    label: t('problem.time'),
    search: {
      component: 'DatePicker',
      componentProps: {
        style: { width: '340px' },
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        StartPlaceholder: 'Start date',
        EndPlaceholder: 'End date'
      }
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    align: 'center',
    fixed: 'right',
    width: 320,
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },

    table: {
      width: 260,
      align: 'left',
      slots: {
        default: (data: any) => {
          const row = data.row
          return (
            <>
              {haspermiss.value.includes('编辑') &&
              row.planStatus == 0 &&
              row.planReleaseStatus == 0 ? (
                <BaseButton type="primary" onClick={() => action(data.row, 'edit')}>
                  {t('exampleDemo.edit')}
                </BaseButton>
              ) : null}

              <BaseButton type="success" onClick={() => action(row, 'detail')}>
                详情
              </BaseButton>
              {/* {row.planReleaseStatus === 1 ? (
                <BaseButton type="warning" onClick={() => action(row, 'detail')}>
                  详情
                </BaseButton>
              ) : null} */}
              {haspermiss.value.includes('删除') && data.row.planReleaseStatus === 0 ? (
                <BaseButton type="danger" onClick={() => delData(data.row)}>
                  {t('exampleDemo.del')}
                </BaseButton>
              ) : null}
            </>
          )
        }
      }
    }
  }
])
// {row.planStatus === 1 && row.videos ? (
//                 <BaseButton type="warning" onClick={() => action(row, 'video')}>
//                   视频
//                 </BaseButton>
//               ) : null}
const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  if (params.date) {
    params.startTime = params.date[0]
    params.endTime = params.date[1]
    delete params.date
  }
  searchParams.value = params
  getList()
}

const dialogVisible = ref(false)
const dialogVisibleVideo = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
  chooes.value = []
}

const delLoading = ref(false)

const ids = ref<string[]>([])

const delData = async (row) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.guid] : elTableExpose?.getSelectionRows().map((v) => v.guid) || []
  delLoading.value = true

  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const videoUrl = ref()
const videoList = ref<VideoDt[]>([])
const action = (row, type: string) => {
  if (type === 'video') {
    dialogVisibleVideo.value = true
    videoList.value = row.videos.map((item: any) => {
      let videoLength = item.videoTime
      let hour = parseInt(videoLength / 3600 + '')
      let minute = parseInt((videoLength % 3600) / 60 + '')
      let second = parseInt((videoLength % 60) + '')
      return {
        ...item,
        videoTime: `${hour}小时${minute}分钟${second}秒`
      }
    })
    return
  }
  dialogVisible.value = true
  actionType.value = type
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')

  let arr: String[] = []
  if (row.planUsers) {
    JSON.parse(row.planUsers).map((i) => {
      arr.push(i.UserNo + '$' + i.UserName + '$' + i.DepNo + '$' + i.DepName)
    })
  }
  let tarr: String[] = []
  if (row.teacherUsers) {
    JSON.parse(row.teacherUsers).map((i) => {
      tarr.push(i.UserNo + '$' + i.UserName + '$' + i.DepNo + '$' + i.DepName)
    })
  }
  let planTime: string[] = []
  if (type === 'edit' && row.planTime) {
    const time = row.planTime.split(' 至 ') //' 一 ' ||
    planTime = [time[0], time[1]]
    console.log('planTime', planTime)
    currentRow.value = {
      ...row,
      chooes: arr,
      chooesTeachers: tarr,
      planTime: planTime,
      isExam: row.isExam == 1 ? true : false,
      IsMissExam: row.IsMissExam == 1 ? true : false
    }
  } else {
    let examArr: string[] = []
    if (row.examUsers) {
      JSON.parse(row.examUsers).map((i) => {
        examArr.push(i.UserNo) //+ '$' + i.UserName + '$' + i.DepNo + '$' + i.DepName
      })
    }

    currentRow.value = {
      ...row,
      chooes: arr,
      chooesTeachers: tarr,
      isExam: row.isExam == 1 ? true : false,
      examArr: examArr
    }
  }
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

// const filterDep = (value: string, data: DepartmentItem) => {}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      console.log('formData---', formData)

      let res
      if (actionType.value == 'edit') {
        formData.guid = currentRow.value.guid
        res = await UpdateCoursePlanApi(formData).finally(() => {
          saveLoading.value = false
        })
      } else {
        res = await AddCoursePlanApi(formData).finally(() => {
          saveLoading.value = false
        })
      }
      if (res) {
        currentPage.value = 1
        getList()
      }
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
      dialogVisible.value = false
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @reset="setSearchParams" @search="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction" v-if="haspermiss.includes('新增')">{{
        t('exampleDemo.add')
      }}</BaseButton>
      <BaseButton
        :loading="delLoading"
        type="danger"
        @click="delData(null)"
        v-if="haspermiss.includes('删除')"
      >
        {{ t('exampleDemo.del') }}
      </BaseButton>
    </div>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :reserveIndex="true"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      :showAction="true"
      :pagination="{
        total
      }"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" :max-height="600">
    <Write
      v-if="actionType !== 'detail' && actionType !== 'video'"
      ref="writeRef"
      :current-row="currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail' && actionType !== 'video'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
  <Dialog v-model="dialogVisibleVideo" title="视频" :fullscreen="false">
    <lookVideos :videoList="videoList" />
    <template #footer>
      <BaseButton @click="dialogVisibleVideo = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
<style lang="scss" scoped>
.videostyle {
  width: 100%;
  height: 100%;
  background: black;
  object-fit: fill;
}
</style>
